<template>
  <div class="role">
      <breadcrumb></breadcrumb>
      <!-- 角色管理卡片 -->
      <el-card>
        <!-- 添加角色按钮，首先要设置行，然后设置列并且设置此列的占据了多少列 -->
        <el-row>
          <el-col :span=6>
            <el-button type="primary" @click="addroles">添加角色</el-button>
          </el-col>
        </el-row>
        <!-- 角色表格制作开始 -->
        <el-table :data="RoleList" style="width: 100%" border stripe>
          <el-table-column  type="expand">
            <template slot-scope="scope">
              <!-- 一级菜单标题渲染 -->
              <el-row :class="['bdbottom', i1==0 ? 'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                <el-col :span=5 >
                  <el-tag effect="dark" closable @close="removeroleById(scope.row,item1.id)" >
                    {{item1.authName}}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二级菜单标题渲染 -->
                <el-col :span=19 >
                  <el-row :class="[i2==0? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id" >
                    <el-col :span=8>
                      <el-tag effect="dark" type="success" closable @close="removeroleById(scope.row,item2.id)">
                        {{item2.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级菜单标题渲染 -->
                    <el-col :span=16>
                      <el-row >
                        <el-tag type="warning" effect="dark" v-for="(item3,i3) in item2.children" 
                        :key="item3.id" closable @close="removeroleById(scope.row,item3.id)">
                                {{item3.authName}}
                        </el-tag>
                        
                      </el-row>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column  type="index">
          </el-table-column>
          <el-table-column  prop="roleName" label="角色名称" >
          </el-table-column>
          <el-table-column  prop="roleDesc" label="角色描述" >
          </el-table-column>
          <el-table-column  label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size='mini' @click="editrole(scope.row.id)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size='mini' @click="deleterole(scope.row.id)">删除</el-button>
              <el-button type="warning" icon="el-icon-setting" size='mini' @click="settingrole(scope.row)">设置权限</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加角色的表单 -->
        <el-dialog title="添加角色" :visible.sync="roledialogVisible" width="50%">
          <el-form ref="addroleref" :model="addroleform" :rules="addrolerules" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addroleform.roleName"></el-input>
            </el-form-item>
             <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addroleform.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
          <el-button @click="cancelroles">取 消</el-button>
          <el-button type="primary" @click="confirmroles">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑角色的表单 -->
        <el-dialog title="编辑角色" :visible.sync="editdialogVisible" width="50%">
          <el-form ref="editroleref" :model="editroleform" :rules="editrolerules" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="editroleform.roleName"></el-input>
            </el-form-item>
             <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="editroleform.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
          <el-button @click="canceledit">取 消</el-button>
          <el-button type="primary" @click="confirmedit">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 设置分配权限的表单 -->
        <el-dialog title="设置分配权限" :visible.sync="settingdialogVisible" width="50%" 
          @close="clearkeys">
            <el-tree ref="settingtree" :data="settingtree" :props="settingprops" show-checkbox node-key="id"
            :default-expand-all="true" :default-checked-keys="seclectkeys" >
            </el-tree>
          <span slot="footer" class="dialog-footer">
          <el-button @click="cancelsetting">取 消</el-button>
          <el-button type="primary" @click="confirmsetting">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
  </div>
</template>


<script>

import breadcrumb from "../../component/content/breadcrumb.vue"
import {netrequest} from "../../network/request.js"

export default {
  name:'role',
  data(){
    return{
      RoleList:null,
      roledialogVisible:false,
      addroleform:{
        roleName:null,
        roleDesc:null
      },
      addrolerules:{
        roleName:[
           { required: true, message: '请输入角色名称', trigger: 'blur' },
           { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc:[
           { required: true, message: '请输入角色描述', trigger: 'blur' },
           { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      },
      editdialogVisible:false,
      editroleform:{},
      editrolerules:{
        roleName:[
           { required: true, message: '请输入角色名称', trigger: 'blur' },
           { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc:[
           { required: true, message: '请输入角色描述', trigger: 'blur' },
           { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      },
      settingdialogVisible:false,
      settingtree:null,
      settingprops:{
        children: 'children',
          label: 'authName'
      },
      seclectkeys:[],
      roleId:null
    }
  },
  components:{
    breadcrumb
  },
  methods:{
    // 获取角色列表数据
    async GetRoleList(){
      // 向服务器请求获取角色列表数据
      const {data:res} = await netrequest({method:'get',url:'/roles'})
      // 把请求的得到的数据保存起来，方便以后使用
      this.RoleList = res.data
      console.log(this.RoleList);
    },
    // 添加角色按钮触发的事件监听
    addroles(){
      this.roledialogVisible = true
    },
    //取消角色添加
    cancelroles(){
      this.$refs.addroleref.resetFields()
      this.roledialogVisible = false
    },
    // 向服务器发送请求添加角色
     confirmroles(){
     this.$refs.addroleref.validate(async (valid)=>{
       if(!valid) return
       const {data:res} = await netrequest({method:'post',url:'/roles',data:this.addroleform})
        if(res.meta.status !== 201)   return
        this.roledialogVisible = false
        this.GetRoleList()
     })
     
     },
    //  编辑角色的信息
    async editrole(id){
      const {data:res} = await netrequest({method:'get',url:'/roles/'+id})
      console.log(res);
      if(res.meta.status !==200) return
      this.editroleform = res.data
      this.editdialogVisible = true
    },
    //确认修改信息向服务器发送网络请求
     confirmedit(){
      this.$refs.editroleref.validate(async valid=>{
        if(!valid) return
        console.log(this.editroleform.id);
        const {data:res} = await netrequest({method:'put',url:'/roles/'+this.editroleform.roleId,
        data:{
        roleName:this.editroleform.roleName,
        roleDesc:this.editroleform.roleDesc
      }
      })
       if(res.meta.status !== 200) return
       this.editdialogVisible = false
       this.GetRoleList()
      })
     
    },
    // 取消对表单的数据验证清除
    canceledit(){
       this.$refs.editroleref.resetFields()
       this.editdialogVisible = false
    },
    // 删除该角色信息
    async deleterole(id){
      const confirmresult = await this.$confirm.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error=>{
          error
        })
        if(confirmresult !== 'confirm') return
        const {data:res} = await netrequest({method:'delete',url:'/roles/'+id})
          if(res.meta.status !== 200) return
          this.GetRoleList()
    },
    // 使用id删除角色权限
    async removeroleById(role,rightId){
     const confirmresult = await this.$confirm.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error=>{
          error
        })
      if(confirmresult !=='confirm') return this.$message.error('删除已取消')
      const {data:res} = await netrequest({method:'delete',url:`roles/${role.id}/rights/${rightId}`})
        if(res.meta.status !==200) return this.$message.error('删除角色权限失败')
        // console.log(res);
        role.children = res.data
    },
    // 设置分配权限
    async settingrole(role){
     const {data:res} = await netrequest({method:'get',url:'rights/tree'})
      if (res.meta.status !==200) return this.$message.error(res.meta.msg)
      this.settingtree = res.data
      this.roleId = role.id
      this.getallkeys(role,this.seclectkeys)
      this.settingdialogVisible = true
    },
    // 递归获得默认选中的key值，因为key值是以id值来识别的，所以获取每个的id值
    getallkeys(role,arr){
      if(!role.children){
        return arr.push(role.id)
      }
      role.children.forEach(items => {
        this.getallkeys(items,arr)
      });
    },
    // 每一次关闭权限对话框之后，都清除一次存放key值的id数组
    clearkeys(){
      this.seclectkeys = [] 
    },
    // 添加角色的权限
    async confirmsetting(){
      const keyarr = [...this.$refs.settingtree.getCheckedKeys(),...this.$refs.settingtree.getHalfCheckedKeys()]
      // console.log(keyarr);
      const strid = keyarr.join(',')
      // console.log(strid);
      const {data:res} = await netrequest({method:'post',url:`/roles/${this.roleId}/rights`,data:{rids:strid}})
      // console.log(res);
      if(res.meta.status !==200) return this.$message.error(res.meta.msg)
      this.settingdialogVisible = false
      this.GetRoleList()
    },
    // 取消
    cancelsetting(){
      this.settingdialogVisible = false
    }
  },
  created(){
    // 获取角色列表数据
    this.GetRoleList()
  }
}
</script>

<style scoped>
.el-tag{
  margin:8px 3px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}

</style>